kaggle - Geospatial Analysis05
import math
import geopandas as gpd
import pandas as pd
from shapely.geometry import MultiPolygon
import folium
from folium import Choropleth, Marker
from folium.plugins import HeatMap, MarkerCluster
def embed_map(m, file_name):
from IPython.display import IFrame
m.save(file_name)
return IFrame(file_name, width='100%', height='500px')
collisions = gpd.read_file("C:/Users/Kangdaeyong/Desktop/datamining/kaggle_geospatial_analysis/archive/NYPD_Motor_Vehicle_Collisions/NYPD_Motor_Vehicle_Collisions/NYPD_Motor_Vehicle_Collisions.shp")
collisions.head()
"LATITUDE" 및 "LONGITUDE" 열을 사용하여 충돌 데이터를 시각화하는 대화형 지도를 만듭니다. 어떤 유형의 지도가 가장 효과적이라고 생각하십니까?
m_1 = folium.Map(location=[40.7, -74], zoom_start=11)
# Your code here: Visualize the collision data
# Visualize the collision data
HeatMap(data=collisions[['LATITUDE', 'LONGITUDE']], radius=9).add_to(m_1)
m_1
hospitals = gpd.read_file("C:/Users/Kangdaeyong/Desktop/datamining/kaggle_geospatial_analysis/archive/nyu_2451_34494/nyu_2451_34494/nyu_2451_34494.shp")
hospitals.head()
"위도" 및 "경도" 열을 사용하여 병원 위치를 시각화합니다.
m_2 = folium.Map(location=[40.7, -74], zoom_start=11)
# Your code here: Visualize the hospital locations
# Visualize the hospital locations
for idx, row in hospitals.iterrows():
Marker([row['latitude'], row['longitude']], popup=row['name']).add_to(m_2)
# Uncomment to see a hint
#q_2.hint()
# Show the map
m_2
outside_range = coverage = gpd.GeoDataFrame(geometry=hospitals.geometry).buffer(10000)
my_union = coverage.geometry.unary_union
outside_range = collisions.loc[~collisions["geometry"].apply(lambda x: my_union.contains(x))]
다음 코드 셀은 가장 가까운 병원에서 10km 이상 떨어진 곳에서 발생한 충돌의 비율을 계산합니다.
percentage = round(100*len(outside_range)/len(collisions), 2)
print("Percentage of collisions more than 10 km away from the closest hospital: {}%".format(percentage))
collisions.head()
def best_hospital(collision_location):
idx_min = hospitals.geometry.distance(collision_location).idxmin()
my_hospital = hospitals.iloc[idx_min]
name = my_hospital["name"]
return name
# Test your function: this should suggest CALVARY HOSPITAL INC
print(best_hospital(outside_range.geometry.iloc[0]))
highest_demand = outside_range.geometry.apply(best_hospital).value_counts().idxmax()
highest_demand
m_6 = folium.Map(location=[40.7, -74], zoom_start=11)
coverage = gpd.GeoDataFrame(geometry=hospitals.geometry).buffer(10000)
folium.GeoJson(coverage.geometry.to_crs(epsg=4326)).add_to(m_6)
HeatMap(data=outside_range[['LATITUDE', 'LONGITUDE']], radius=9).add_to(m_6)
folium.LatLngPopup().add_to(m_6)
m_6
지도의 아무 곳이나 클릭하면 해당 위치의 위도 및 경도 팝업이 표시됩니다.
New York 시는 두 곳의 새로운 병원을 지을 위치를 결정하는 데 도움을 드리기 위해 연락을 드립니다. 그들은 특히 3) 단계에서 계산된 백분율을 10% 미만으로 만들기 위해 위치 식별에 대한 귀하의 도움을 원합니다. 지도를 사용하여(지역 설정법이나 병원을 건설하기 위해 제거해야 할 잠재적 건물에 대해 걱정하지 않고) 도시가 이 목표를 달성하는 데 도움이 되는 두 위치를 식별할 수 있습니까?
병원 1에 대해 제안된 위도와 경도를 각각 lat_1과 long_1에 넣습니다. (병원2도 마찬가지)
그런 다음 나머지 셀을 그대로 실행하여 새 병원의 효과를 확인하십시오. 두 개의 새로운 병원에서 백분율을 10% 미만으로 낮추면 답이 정답으로 표시됩니다.
lat_1 = 40.6714
long_1 = -73.8492
# Proposed location of hospital 2
lat_2 = 40.6702
long_2 = -73.7612
# Do not modify the code below this line
try:
new_df = pd.DataFrame(
{'Latitude': [lat_1, lat_2],
'Longitude': [long_1, long_2]})
new_gdf = gpd.GeoDataFrame(new_df, geometry=gpd.points_from_xy(new_df.Longitude, new_df.Latitude))
new_gdf.crs = {'init' :'epsg:4326'}
new_gdf = new_gdf.to_crs(epsg=2263)
# get new percentage
new_coverage = gpd.GeoDataFrame(geometry=new_gdf.geometry).buffer(10000)
new_my_union = new_coverage.geometry.unary_union
new_outside_range = outside_range.loc[~outside_range["geometry"].apply(lambda x: new_my_union.contains(x))]
new_percentage = round(100*len(new_outside_range)/len(collisions), 2)
print("(NEW) Percentage of collisions more than 10 km away from the closest hospital: {}%".format(new_percentage))
# Did you help the city to meet its goal?
q_6.check()
# make the map
m = folium.Map(location=[40.7, -74], zoom_start=11)
folium.GeoJson(coverage.geometry.to_crs(epsg=4326)).add_to(m)
folium.GeoJson(new_coverage.geometry.to_crs(epsg=4326)).add_to(m)
for idx, row in new_gdf.iterrows():
Marker([row['Latitude'], row['Longitude']]).add_to(m)
HeatMap(data=new_outside_range[['LATITUDE', 'LONGITUDE']], radius=9).add_to(m)
folium.LatLngPopup().add_to(m)
display(embed_map(m, 'q_6.html'))
except:
print('a')